/**
 * 详情页面功能
 */

document.addEventListener('DOMContentLoaded', function() {
    // 初始化返回按钮
    initBackButton();
    
    // 初始化Tab导航
    initDetailNav();
    
    // 初始化收藏按钮
    initCollectButton();
    
    // 初始化申请按钮
    initApplyBtn();
    
    // 初始化岗位相关操作
    initJobActions();
    
    // 初始化活动相关操作
    initEventActions();
    
    // 处理图片加载错误
    handleImageErrors();
    
    // 初始化滚动动画
    initScrollAnimation();
    
    // 初始化分享按钮
    initShareButton();
    
    // 加载详情数据
    loadDetailData();
    
    // 加载校园活动数据
    loadSchoolEvents();
});

/**
 * 初始化返回按钮
 */
function initBackButton() {
    const backBtn = document.querySelector('.back-btn');
    if (backBtn) {
        backBtn.addEventListener('click', function() {
            window.history.back();
        });
    }
}

/**
 * 初始化Tab导航
 */
function initDetailNav() {
    const navItems = document.querySelectorAll('.nav-item');
    const contentSections = document.querySelectorAll('.content-section');
    
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            // 移除所有导航项的active类
            navItems.forEach(nav => nav.classList.remove('active'));
            
            // 为当前点击项添加active类
            this.classList.add('active');
            
            // 获取目标内容ID
            const targetId = this.getAttribute('data-target');
            
            // 隐藏所有内容区域
            contentSections.forEach(section => section.classList.remove('active'));
            
            // 显示目标内容区域
            const targetSection = document.getElementById(targetId);
            if (targetSection) {
                targetSection.classList.add('active');
            }
        });
    });
}

/**
 * 初始化收藏按钮
 */
function initCollectButton() {
    const collectBtn = document.querySelector('.collect-btn');
    if (collectBtn) {
        collectBtn.addEventListener('click', function() {
            this.classList.toggle('active');
            const isCollected = this.classList.contains('active');
            
            // 获取当前页面类型和ID
            const pageType = getPageType();
            const id = getIdFromUrl();
            
            if (isCollected) {
                // 添加收藏
                addToCollection(pageType, id);
                showToast('收藏成功');
            } else {
                // 取消收藏
                removeFromCollection(pageType, id);
                showToast('已取消收藏');
            }
        });
    }
}

/**
 * 添加到收藏
 */
function addToCollection(type, id) {
    // 获取本地存储中的收藏数据
    let collections = localStorage.getItem('collections');
    collections = collections ? JSON.parse(collections) : {};
    
    // 初始化类型对应的收藏数组
    if (!collections[type]) {
        collections[type] = [];
    }
    
    // 添加到收藏，避免重复
    if (!collections[type].includes(id)) {
        collections[type].push(id);
    }
    
    // 存回本地存储
    localStorage.setItem('collections', JSON.stringify(collections));
}

/**
 * 从收藏中移除
 */
function removeFromCollection(type, id) {
    // 获取本地存储中的收藏数据
    let collections = localStorage.getItem('collections');
    if (!collections) return;
    
    collections = JSON.parse(collections);
    
    // 如果没有对应类型的收藏，直接返回
    if (!collections[type]) return;
    
    // 从数组中移除
    const index = collections[type].indexOf(id);
    if (index > -1) {
        collections[type].splice(index, 1);
    }
    
    // 存回本地存储
    localStorage.setItem('collections', JSON.stringify(collections));
}

/**
 * 获取页面类型
 */
function getPageType() {
    const path = window.location.pathname;
    if (path.includes('school-detail')) {
        return 'school';
    } else if (path.includes('company-detail')) {
        return 'company';
    }
    return '';
}

/**
 * 从URL获取ID
 */
function getIdFromUrl() {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('id') || '1'; // 默认返回1
}

/**
 * 显示提示信息
 */
function showToast(message) {
    // 创建toast元素
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    
    // 添加到文档
    document.body.appendChild(toast);
    
    // 应用样式
    toast.style.position = 'fixed';
    toast.style.bottom = '100px';
    toast.style.left = '50%';
    toast.style.transform = 'translateX(-50%)';
    toast.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    toast.style.color = 'white';
    toast.style.padding = '8px 16px';
    toast.style.borderRadius = '4px';
    toast.style.zIndex = '2000';
    toast.style.transition = 'opacity 0.3s';
    
    // 显示toast
    setTimeout(() => {
        toast.style.opacity = '1';
    }, 10);
    
    // 2秒后隐藏并移除
    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 2000);
}

/**
 * 加载详情数据
 */
function loadDetailData() {
    const pageType = getPageType();
    const id = getIdFromUrl();
    
    if (!id) return;
    
    if (pageType === 'school') {
        loadSchoolDetail(id);
    } else if (pageType === 'company') {
        loadCompanyDetail(id);
    }
}

/**
 * 加载院校详情
 */
function loadSchoolDetail(id) {
    // 模拟数据，实际项目中应从API获取
    const schoolData = {
        id: id,
        name: '北京大学',
        cover: 'https://source.unsplash.com/random/800x400/?university,campus',
        tags: ['985工程', '211工程', '综合类', '研究型'],
        intro: '北京大学（Peking University），简称"北大"，是中国近代第一所国立综合性大学，创办于1898年，初名京师大学堂。是中国最著名的大学之一，在中国现代史上具有重要地位。',
        basicInfo: [
            { label: '创办时间', value: '1898年' },
            { label: '学校类型', value: '综合类' },
            { label: '所在地区', value: '北京市' },
            { label: '隶属关系', value: '教育部' },
            { label: '院士人数', value: '100+' },
            { label: '占地面积', value: '2,743,532平方米' },
        ],
        campusImages: [
            'https://source.unsplash.com/random/300x300/?university,campus1',
            'https://source.unsplash.com/random/300x300/?university,campus2',
            'https://source.unsplash.com/random/300x300/?university,campus3',
            'https://source.unsplash.com/random/300x300/?university,campus4',
            'https://source.unsplash.com/random/300x300/?university,campus5',
            'https://source.unsplash.com/random/300x300/?university,campus6',
        ],
        featuredMajors: [
            { name: '计算机科学与技术', desc: '国家一流建设学科，培养高素质计算机人才' },
            { name: '数学', desc: '国家重点学科，拥有多位著名数学家' },
            { name: '物理学', desc: '国家重点学科，注重培养科研能力' },
            { name: '经济学', desc: '国家重点学科，毕业生就业前景广阔' },
        ],
        colleges: [
            { 
                name: '信息科学技术学院',
                majors: ['计算机科学与技术', '软件工程', '电子信息科学', '人工智能']
            },
            { 
                name: '理学院',
                majors: ['数学', '物理学', '化学', '生物科学']
            },
            { 
                name: '经济学院',
                majors: ['经济学', '金融学', '国际经济与贸易']
            },
        ],
        employmentRate: '98.5%',
        employmentDesc: '2022年本科毕业生就业率',
        employmentChart: {
            // 就业去向统计数据
        },
        employmentCompanies: [
            '腾讯', '阿里巴巴', '华为', '百度', '字节跳动', '中国工商银行', '中国建设银行'
        ],
        alumni: [
            { name: '李某某', title: '某科技公司CEO', avatar: 'https://i.pravatar.cc/100?img=1' },
            { name: '张某某', title: '著名科学家', avatar: 'https://i.pravatar.cc/100?img=2' },
            { name: '王某某', title: '知名企业家', avatar: 'https://i.pravatar.cc/100?img=3' },
        ],
        alumniEvents: [
            { title: '校友返校日', date: '2023-05-20', desc: '年度校友返校交流活动' },
            { title: '创业校友分享会', date: '2023-06-15', desc: '优秀创业校友经验分享' },
        ],
        relatedSchools: [
            { id: 2, name: '清华大学', image: 'https://source.unsplash.com/random/300x200/?university1' },
            { id: 3, name: '复旦大学', image: 'https://source.unsplash.com/random/300x200/?university2' },
            { id: 4, name: '上海交通大学', image: 'https://source.unsplash.com/random/300x200/?university3' },
            { id: 5, name: '浙江大学', image: 'https://source.unsplash.com/random/300x200/?university4' },
        ]
    };
    
    // 渲染学校详情数据
    renderSchoolDetail(schoolData);
}

/**
 * 渲染院校详情
 */
function renderSchoolDetail(data) {
    // 更新标题和横幅
    document.title = `${data.name} - 就业指引`;
    
    // 设置学校封面和信息
    const cover = document.querySelector('.school-cover');
    const name = document.querySelector('.school-name');
    const tags = document.querySelector('.school-tags');
    
    if (cover) cover.src = data.cover;
    if (cover) cover.alt = data.name;
    if (name) name.textContent = data.name;
    
    if (tags) {
        tags.innerHTML = '';
        data.tags.forEach(tag => {
            const tagEl = document.createElement('span');
            tagEl.className = 'tag';
            tagEl.textContent = tag;
            tags.appendChild(tagEl);
        });
    }
    
    // 渲染学校简介
    const intro = document.querySelector('.school-intro');
    if (intro) intro.textContent = data.intro;
    
    // 渲染基本信息
    const infoList = document.querySelector('.info-list');
    if (infoList) {
        infoList.innerHTML = '';
        data.basicInfo.forEach(info => {
            const infoItem = document.createElement('div');
            infoItem.className = 'info-item';
            infoItem.innerHTML = `
                <div class="info-label">${info.label}</div>
                <div class="info-value">${info.value}</div>
            `;
            infoList.appendChild(infoItem);
        });
    }
    
    // 渲染校园图片
    const campusGallery = document.querySelector('.campus-gallery');
    if (campusGallery) {
        campusGallery.innerHTML = '';
        data.campusImages.forEach(img => {
            const galleryItem = document.createElement('div');
            galleryItem.className = 'gallery-item';
            galleryItem.innerHTML = `<img src="${img}" alt="校园环境">`;
            campusGallery.appendChild(galleryItem);
        });
    }
    
    // 渲染重点专业
    const featuredMajors = document.querySelector('.major-list.featured');
    if (featuredMajors) {
        featuredMajors.innerHTML = '';
        data.featuredMajors.forEach(major => {
            const majorItem = document.createElement('div');
            majorItem.className = 'major-item';
            majorItem.innerHTML = `
                <div class="major-name">${major.name}</div>
                <div class="major-desc">${major.desc}</div>
            `;
            featuredMajors.appendChild(majorItem);
        });
    }
    
    // 渲染学院专业列表
    const collegeList = document.querySelector('.college-list');
    if (collegeList) {
        collegeList.innerHTML = '';
        data.colleges.forEach(college => {
            const collegeItem = document.createElement('div');
            collegeItem.className = 'college-item';
            
            let majorTags = '';
            college.majors.forEach(major => {
                majorTags += `<span class="major-tag">${major}</span>`;
            });
            
            collegeItem.innerHTML = `
                <div class="college-name">${college.name}</div>
                <div class="major-tags">${majorTags}</div>
            `;
            collegeList.appendChild(collegeItem);
        });
    }
    
    // 渲染就业率
    const employmentRate = document.querySelector('.employment-rate');
    if (employmentRate) {
        employmentRate.innerHTML = `
            <div class="rate-number">${data.employmentRate}</div>
            <div class="rate-desc">${data.employmentDesc}</div>
        `;
    }
    
    // 渲染就业企业
    const companyList = document.querySelector('.company-list');
    if (companyList) {
        companyList.innerHTML = '';
        const companyTags = data.employmentCompanies.map(company => 
            `<span class="major-tag">${company}</span>`
        ).join('');
        companyList.innerHTML = `<div class="major-tags">${companyTags}</div>`;
    }
    
    // 渲染相关学校推荐
    const relatedList = document.querySelector('.related-list');
    if (relatedList) {
        relatedList.innerHTML = '';
        data.relatedSchools.forEach(school => {
            const relatedItem = document.createElement('div');
            relatedItem.className = 'related-item';
            relatedItem.setAttribute('data-id', school.id);
            relatedItem.innerHTML = `
                <img src="${school.image}" alt="${school.name}" class="related-image">
                <div class="related-name">${school.name}</div>
            `;
            relatedItem.addEventListener('click', function() {
                window.location.href = `school-detail.html?id=${school.id}`;
            });
            relatedList.appendChild(relatedItem);
        });
    }
}

/**
 * 加载企业详情
 */
function loadCompanyDetail(id) {
    // 模拟数据，实际项目中应从API获取
    const companyData = {
        id: id,
        name: '腾讯',
        cover: 'https://source.unsplash.com/random/800x400/?office,tech',
        tags: ['互联网', '科技', '游戏', '社交'],
        intro: '腾讯是中国领先的互联网增值服务提供商之一，成立于1998年，总部位于中国深圳。公司主要业务包括社交网络、门户网站、即时通信工具、网络游戏、电子商务、互联网广告、云计算等多项服务。',
        basicInfo: [
            { label: '成立时间', value: '1998年' },
            { label: '公司规模', value: '10万+人' },
            { label: '总部地点', value: '广东省深圳市' },
            { label: '行业', value: '互联网' },
            { label: '上市情况', value: '港交所上市' },
            { label: '年营收', value: '5000+亿元' },
        ],
        officeImages: [
            'https://source.unsplash.com/random/300x300/?office1',
            'https://source.unsplash.com/random/300x300/?office2',
            'https://source.unsplash.com/random/300x300/?office3',
            'https://source.unsplash.com/random/300x300/?office4',
            'https://source.unsplash.com/random/300x300/?office5',
            'https://source.unsplash.com/random/300x300/?office6',
        ],
        positions: [
            { name: '后端开发工程师', desc: '负责服务端架构设计和开发工作' },
            { name: '前端开发工程师', desc: '负责前端界面设计和交互开发' },
            { name: '产品经理', desc: '负责产品规划、需求分析和功能设计' },
            { name: '数据分析师', desc: '负责数据挖掘、分析和可视化展示' },
        ],
        recruitmentPlan: [
            { title: '2023秋季校招', details: ['本科及以上学历', '计算机相关专业', '9月开始', '全国招聘'] },
            { title: '2024春季实习生招聘', details: ['大三及以上在校生', '计算机、数学、经济相关专业', '3月开始'] }
        ],
        internships: [
            { name: '技术研发实习生', desc: '参与实际项目开发，导师1对1指导' },
            { name: '产品实习生', desc: '参与产品设计流程，积累实战经验' },
            { name: '运营实习生', desc: '参与平台运营工作，提升数据分析能力' },
        ],
        values: [
            { title: '用户为本', desc: '一切以用户价值为依归，为用户创造价值' },
            { title: '科技向善', desc: '运用科技手段，让世界更美好' },
            { title: '拥抱变化', desc: '保持开放心态，积极应对变化' },
        ],
        benefits: [
            '弹性工作制', '年度旅游', '丰厚奖金', '股票期权', '健身房', '免费三餐', '定期体检'
        ],
        activities: [
            { title: '团队拓展', image: 'https://source.unsplash.com/random/300x200/?team1' },
            { title: '年度晚会', image: 'https://source.unsplash.com/random/300x200/?party1' },
            { title: '技术分享会', image: 'https://source.unsplash.com/random/300x200/?meeting1' },
        ],
        rating: '4.8',
        ratingDesc: '基于2000+员工评价',
        reviews: [
            {
                name: '匿名用户',
                avatar: 'https://i.pravatar.cc/100?img=4',
                rating: 5,
                date: '2023-03-15',
                content: '公司福利好，技术氛围浓厚，能接触到前沿技术和大型项目，团队协作愉快。'
            },
            {
                name: '匿名用户',
                avatar: 'https://i.pravatar.cc/100?img=5',
                rating: 4,
                date: '2023-02-20',
                content: '工作压力有点大，但能学到很多东西，晋升机制也比较透明。'
            },
        ],
        relatedCompanies: [
            { id: 2, name: '阿里巴巴', image: 'https://source.unsplash.com/random/300x200/?company1' },
            { id: 3, name: '百度', image: 'https://source.unsplash.com/random/300x200/?company2' },
            { id: 4, name: '字节跳动', image: 'https://source.unsplash.com/random/300x200/?company3' },
            { id: 5, name: '华为', image: 'https://source.unsplash.com/random/300x200/?company4' },
        ]
    };
    
    // 渲染企业详情数据
    renderCompanyDetail(companyData);
}

/**
 * 渲染企业详情
 */
function renderCompanyDetail(data) {
    // 更新标题和横幅
    document.title = `${data.name} - 就业指引`;
    
    // 设置企业封面和信息
    const cover = document.querySelector('.company-cover');
    const name = document.querySelector('.company-name');
    const tags = document.querySelector('.company-tags');
    
    if (cover) cover.src = data.cover;
    if (cover) cover.alt = data.name;
    if (name) name.textContent = data.name;
    
    if (tags) {
        tags.innerHTML = '';
        data.tags.forEach(tag => {
            const tagEl = document.createElement('span');
            tagEl.className = 'tag';
            tagEl.textContent = tag;
            tags.appendChild(tagEl);
        });
    }
    
    // 渲染企业简介
    const intro = document.querySelector('.company-intro');
    if (intro) intro.textContent = data.intro;
    
    // 渲染基本信息
    const infoList = document.querySelector('.info-list');
    if (infoList) {
        infoList.innerHTML = '';
        data.basicInfo.forEach(info => {
            const infoItem = document.createElement('div');
            infoItem.className = 'info-item';
            infoItem.innerHTML = `
                <div class="info-label">${info.label}</div>
                <div class="info-value">${info.value}</div>
            `;
            infoList.appendChild(infoItem);
        });
    }
    
    // 渲染办公环境图片
    const officeGallery = document.querySelector('.office-gallery');
    if (officeGallery) {
        officeGallery.innerHTML = '';
        data.officeImages.forEach(img => {
            const galleryItem = document.createElement('div');
            galleryItem.className = 'gallery-item';
            galleryItem.innerHTML = `<img src="${img}" alt="办公环境">`;
            officeGallery.appendChild(galleryItem);
        });
    }
    
    // 渲染热招职位
    const positionList = document.querySelector('.position-list');
    if (positionList) {
        positionList.innerHTML = '';
        data.positions.forEach(position => {
            const positionItem = document.createElement('div');
            positionItem.className = 'position-item';
            positionItem.innerHTML = `
                <div class="position-name">${position.name}</div>
                <div class="position-desc">${position.desc}</div>
            `;
            positionList.appendChild(positionItem);
        });
    }
    
    // 渲染校招计划
    const recruitmentPlan = document.querySelector('.recruitment-plan');
    if (recruitmentPlan) {
        recruitmentPlan.innerHTML = '';
        data.recruitmentPlan.forEach(plan => {
            const planItem = document.createElement('div');
            planItem.className = 'plan-item';
            
            let detailTags = '';
            plan.details.forEach(detail => {
                detailTags += `<span class="major-tag">${detail}</span>`;
            });
            
            planItem.innerHTML = `
                <div class="plan-title">${plan.title}</div>
                <div class="plan-details">${detailTags}</div>
            `;
            recruitmentPlan.appendChild(planItem);
        });
    }
    
    // 渲染实习机会
    const internshipList = document.querySelector('.internship-list');
    if (internshipList) {
        internshipList.innerHTML = '';
        data.internships.forEach(internship => {
            const internshipItem = document.createElement('div');
            internshipItem.className = 'internship-item';
            internshipItem.innerHTML = `
                <div class="internship-name">${internship.name}</div>
                <div class="internship-desc">${internship.desc}</div>
            `;
            internshipList.appendChild(internshipItem);
        });
    }
    
    // 渲染评分
    const rating = document.querySelector('.overall-rating');
    if (rating) {
        rating.innerHTML = `
            <div class="rating-number">${data.rating}</div>
            <div class="rating-desc">${data.ratingDesc}</div>
        `;
    }
    
    // 渲染相关企业推荐
    const relatedList = document.querySelector('.related-list');
    if (relatedList) {
        relatedList.innerHTML = '';
        data.relatedCompanies.forEach(company => {
            const relatedItem = document.createElement('div');
            relatedItem.className = 'related-item';
            relatedItem.setAttribute('data-id', company.id);
            relatedItem.innerHTML = `
                <img src="${company.image}" alt="${company.name}" class="related-image">
                <div class="related-name">${company.name}</div>
            `;
            relatedItem.addEventListener('click', function() {
                window.location.href = `company-detail.html?id=${company.id}`;
            });
            relatedList.appendChild(relatedItem);
        });
    }
}

/**
 * 初始化申请按钮
 */
function initApplyBtn() {
    const applyBtn = document.querySelector('.action-buttons .apply-btn');
    if (applyBtn) {
        applyBtn.addEventListener('click', function() {
            const pageType = getPageType();
            if (pageType === 'school') {
                showToast('申请信息已提交，稍后将有顾问联系您');
            } else {
                showToast('简历投递成功，请留意系统通知');
            }
        });
    }
}

/**
 * 初始化岗位相关操作
 */
function initJobActions() {
    // 处理岗位申请按钮点击
    const applyJobBtns = document.querySelectorAll('.apply-now-btn');
    applyJobBtns.forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const jobItem = this.closest('.job-item');
            const jobId = jobItem?.getAttribute('data-id');
            const jobTitle = jobItem?.querySelector('.job-title')?.textContent || '该职位';
            
            // 确认是否申请
            if (confirm(`确定要申请"${jobTitle}"吗？`)) {
                // 更改按钮状态
                this.textContent = '已申请';
                this.disabled = true;
                this.style.backgroundColor = '#999';
                
                // 记录申请状态
                if (jobId) {
                    saveJobApplication(jobId);
                }
                
                // 显示提示
                showToast('申请成功，请留意通知');
            }
        });
    });
    
    // 处理整个岗位卡片的点击
    const jobItems = document.querySelectorAll('.job-item');
    jobItems.forEach(item => {
        const jobLink = item.querySelector('.job-link');
        if (jobLink) {
            item.addEventListener('click', function(e) {
                // 如果点击的不是按钮，则跳转到详情页
                if (!e.target.closest('.apply-now-btn')) {
                    window.location.href = jobLink.getAttribute('href');
                }
            });
        }
    });
    
    // 处理查看更多按钮
    const viewMoreLinks = document.querySelectorAll('.view-more-link');
    viewMoreLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            // 添加过渡动画
            addTransitionAnimation(e);
        });
    });
}

/**
 * 初始化活动相关操作
 */
function initEventActions() {
    // 为所有事件项添加点击波纹效果
    const eventItems = document.querySelectorAll('.event-item');
    eventItems.forEach(item => {
        item.addEventListener('click', function(e) {
            const rect = this.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const ripple = document.createElement('span');
            ripple.className = 'ripple-effect';
            ripple.style.left = `${x}px`;
            ripple.style.top = `${y}px`;
            
            this.appendChild(ripple);
            
            setTimeout(() => {
                ripple.remove();
            }, 600);
        });
    });
    
    // 图片渐入效果
    const eventImages = document.querySelectorAll('.event-image img');
    eventImages.forEach(img => {
        img.style.opacity = '0';
        img.onload = function() {
            setTimeout(() => {
                this.style.transition = 'opacity 0.3s ease';
                this.style.opacity = '1';
            }, 100);
        };
        // 如果图片已经加载完成
        if (img.complete) {
            img.style.opacity = '1';
        }
    });
}

/**
 * 初始化滚动动画
 */
function initScrollAnimation() {
    // 添加页面滚动效果
    window.addEventListener('scroll', function() {
        const header = document.querySelector('.header');
        if (window.scrollY > 60) {
            header?.classList.add('header-scrolled');
        } else {
            header?.classList.remove('header-scrolled');
        }
        
        // 添加元素进入视口时的动画
        const elements = document.querySelectorAll('.job-item, .event-item, .value-item, .benefit-item, .plan-card');
        elements.forEach(el => {
            const rect = el.getBoundingClientRect();
            const isInViewport = rect.top < window.innerHeight * 0.9 && rect.bottom > 0;
            
            if (isInViewport) {
                el.classList.add('visible');
            }
        });
    });
    
    // 触发一次滚动事件以应用初始动画
    setTimeout(() => {
        window.dispatchEvent(new Event('scroll'));
    }, 100);
}

/**
 * 初始化分享按钮
 */
function initShareButton() {
    const shareBtn = document.querySelector('.share-btn');
    if (shareBtn) {
        shareBtn.addEventListener('click', function() {
            // 获取页面信息
            const pageTitle = document.title;
            const pageUrl = window.location.href;
            
            // 如果支持原生分享API
            if (navigator.share) {
                navigator.share({
                    title: pageTitle,
                    url: pageUrl
                })
                .then(() => {
                    console.log('分享成功');
                })
                .catch(error => {
                    console.log('分享失败:', error);
                    showShareFallback(pageTitle, pageUrl);
                });
            } else {
                // 不支持原生分享时的回退方案
                showShareFallback(pageTitle, pageUrl);
            }
        });
    }
}

/**
 * 显示分享回退选项
 */
function showShareFallback(title, url) {
    // 创建分享面板
    let sharePanel = document.querySelector('.share-panel');
    
    if (!sharePanel) {
        sharePanel = document.createElement('div');
        sharePanel.className = 'share-panel';
        
        // 添加面板内容
        sharePanel.innerHTML = `
            <div class="share-panel-content">
                <div class="share-panel-header">
                    <h3>分享到</h3>
                    <button class="close-btn"><i class="iconfont icon-close"></i></button>
                </div>
                <div class="share-options">
                    <button class="share-option wechat">
                        <i class="iconfont icon-wechat"></i>
                        <span>微信</span>
                    </button>
                    <button class="share-option weibo">
                        <i class="iconfont icon-weibo"></i>
                        <span>微博</span>
                    </button>
                    <button class="share-option qq">
                        <i class="iconfont icon-QQ"></i>
                        <span>QQ</span>
                    </button>
                    <button class="share-option copy-link">
                        <i class="iconfont icon-link"></i>
                        <span>复制链接</span>
                    </button>
                </div>
            </div>
        `;
        
        document.body.appendChild(sharePanel);
        
        // 添加关闭按钮事件
        const closeBtn = sharePanel.querySelector('.close-btn');
        closeBtn.addEventListener('click', function() {
            sharePanel.classList.remove('show');
        });
        
        // 添加复制链接功能
        const copyBtn = sharePanel.querySelector('.copy-link');
        copyBtn.addEventListener('click', function() {
            const textArea = document.createElement('textarea');
            textArea.value = url;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            
            showToast('链接已复制');
            sharePanel.classList.remove('show');
        });
        
        // 添加其他分享选项的点击事件
        const shareOptions = sharePanel.querySelectorAll('.share-option:not(.copy-link)');
        shareOptions.forEach(option => {
            option.addEventListener('click', function() {
                showToast('请使用浏览器自带分享功能');
                sharePanel.classList.remove('show');
            });
        });
    }
    
    // 显示分享面板
    sharePanel.classList.add('show');
}

/**
 * 保存职位申请状态
 */
function saveJobApplication(jobId) {
    const appliedJobs = JSON.parse(localStorage.getItem('appliedJobs') || '[]');
    
    if (!appliedJobs.includes(jobId)) {
        appliedJobs.push(jobId);
    }
    
    localStorage.setItem('appliedJobs', JSON.stringify(appliedJobs));
}

/**
 * 添加页面过渡动画
 */
function addTransitionAnimation(event) {
    // 创建动画效果
    const target = event.currentTarget;
    const rect = target.getBoundingClientRect();
    
    // 创建动画点
    const circle = document.createElement('div');
    circle.className = 'click-effect';
    circle.style.left = `${event.clientX - rect.left}px`;
    circle.style.top = `${event.clientY - rect.top}px`;
    target.appendChild(circle);
    
    // 设置动画结束后移除元素
    setTimeout(() => {
        circle.remove();
    }, 300);
}

/**
 * 处理图片加载错误
 */
function handleImageErrors() {
    const images = document.querySelectorAll('img');
    
    images.forEach(img => {
        // 如果图片已经加载完成且有错误，替换图片
        if (img.complete && (img.naturalWidth === 0 || img.naturalHeight === 0)) {
            replaceWithAlternativeImage(img);
        }
        
        // 图片加载错误时的处理
        img.onerror = function() {
            replaceWithAlternativeImage(this);
        };
    });
    
    // 替换图片
    function replaceWithAlternativeImage(img) {
        // 确定图片类型
        let imgType = 'general';
        let width = 300;
        let height = 200;
        
        if (img.classList.contains('school-cover') || img.classList.contains('company-cover')) {
            imgType = 'cover';
            width = 800;
            height = 400;
        } else if (img.classList.contains('company-logo')) {
            imgType = 'logo';
            width = 80;
            height = 80;
        } else if (img.parentElement && img.parentElement.classList.contains('gallery-item')) {
            imgType = 'gallery';
            width = 300;
            height = 200;
        }
        
        // 生成随机ID
        const randomId = Math.floor(Math.random() * 1000);
        
        // 设置不同类型的图片源
        switch (imgType) {
            case 'cover':
                img.src = `https://source.unsplash.com/featured/${width}x${height}/?business,company/${randomId}`;
                break;
            case 'logo':
                img.src = `https://source.unsplash.com/featured/${width}x${height}/?logo,brand/${randomId}`;
                break;
            case 'gallery':
                img.src = `https://source.unsplash.com/featured/${width}x${height}/?office,workspace/${randomId}`;
                break;
            default:
                img.src = `https://source.unsplash.com/featured/${width}x${height}/?business/${randomId}`;
        }
        
        // 设置为急切加载以提高优先级
        img.loading = 'eager';
    }
}

/**
 * 加载校园活动数据
 */
function loadSchoolEvents() {
    // 检查是否存在校园活动列表元素
    const eventList = document.querySelector('.event-list');
    if (!eventList) return;
    
    // 添加加载中状态
    eventList.classList.add('loading');
    eventList.innerHTML = '';
    
    // 模拟异步加载
    setTimeout(() => {
        // 清除加载状态
        eventList.classList.remove('loading');
        
        // 模拟从服务器获取数据
        const eventsData = [
            {
                id: 'a1',
                title: '2023届毕业生春季招聘会',
                image: 'https://source.unsplash.com/featured/300x200/?job,fair/1',
                status: 'ongoing',
                time: '2023-05-25 09:00-17:00',
                location: '北京大学就业中心',
                participants: 1500
            },
            {
                id: 'a2',
                title: 'AI与大数据技术交流会',
                image: 'https://source.unsplash.com/featured/300x200/?technology,conference/2',
                status: 'upcoming',
                time: '2023-06-10 14:00-16:30',
                location: '北京大学信息科学楼',
                participants: 600
            },
            {
                id: 'a3',
                title: '校企合作创新论坛',
                image: 'https://source.unsplash.com/featured/300x200/?business,forum/3',
                status: 'upcoming',
                time: '2023-06-20 10:00-12:00',
                location: '北京大学经管学院',
                participants: 450
            },
            {
                id: 'a4',
                title: '2023国际学术交流周',
                image: 'https://source.unsplash.com/featured/300x200/?academic,conference/4',
                status: 'upcoming',
                time: '2023-07-05 全天',
                location: '北京大学多功能厅',
                participants: 800
            },
            {
                id: 'a5',
                title: '互联网产业创新发展峰会',
                image: 'https://source.unsplash.com/featured/300x200/?internet,summit/5',
                status: 'upcoming',
                time: '2023-07-15 13:30-17:00',
                location: '北京大学国际会议中心',
                participants: 950
            }
        ];
        
        // 检查数据是否为空
        if (eventsData.length === 0) {
            // 显示空状态
            eventList.innerHTML = `
                <div class="empty-state">
                    <div class="icon">
                        <i class="bi bi-calendar-x"></i>
                    </div>
                    <div class="text">暂无近期校园活动</div>
                </div>
            `;
            return;
        }
        
        // 生成HTML并添加到页面
        eventsData.forEach(event => {
            const eventItem = document.createElement('a');
            eventItem.href = `activity-detail.html?id=${event.id}`;
            eventItem.className = 'event-item';
            
            const statusText = {
                'ongoing': '进行中',
                'upcoming': '即将开始',
                'ended': '已结束'
            };
            
            eventItem.innerHTML = `
                <div class="event-image">
                    <img src="${event.image}" alt="${event.title}" loading="eager">
                    <div class="event-status ${event.status}">${statusText[event.status]}</div>
                </div>
                <div class="event-info">
                    <h3 class="event-title">${event.title}</h3>
                    <div class="event-time"><i class="bi bi-clock"></i> ${event.time}</div>
                    <div class="event-location"><i class="bi bi-geo-alt"></i> ${event.location}</div>
                    <div class="event-participants"><i class="bi bi-people"></i> ${event.participants}人参与</div>
                </div>
            `;
            
            // 添加到DOM
            eventList.appendChild(eventItem);
        });
        
        // 添加"查看更多"按钮
        const moreBtn = document.createElement('div');
        moreBtn.className = 'view-more-events';
        moreBtn.innerHTML = '<button class="view-more-btn">查看更多校园活动 <i class="bi bi-arrow-right"></i></button>';
        eventList.appendChild(moreBtn);
        
        // 添加事件监听
        moreBtn.querySelector('.view-more-btn').addEventListener('click', function() {
            window.location.href = 'activities.html?type=school&id=' + getIdFromUrl();
        });
        
        // 初始化事件操作
        initEventActions();
    }, 1000); // 模拟1秒的加载时间
} 